"""
地图编辑器模块
包含地图编辑器的所有功能
"""

import pygame
import json
import os
from settings import *
from sprites import Obstacle, Monster

class MapEditor:
    """地图编辑器类"""
    
    def __init__(self, game):
        """初始化地图编辑器"""
        self.game = game
        self.input_text = ""
        self.input_active = False

    def editor_events(self, event):
        """处理地图编辑器中的事件"""
        # 左键拖拽绘制障碍物
        if event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:  # 左键
                self.game.editor_drawing = True
                self.game.editor_start_pos = event.pos
            # 右键删除障碍物或野怪
            elif event.button == 3:  # 右键
                # 删除障碍物
                for obstacle in self.game.obstacles:
                    if obstacle.rect.collidepoint(event.pos):
                        obstacle.kill()
                        break
                
                # 删除野怪
                for monster in self.game.monsters:
                    if monster.rect.collidepoint(event.pos):
                        monster.kill()
                        break
                        
            # 中键放置/删除野怪
            elif event.button == 2:  # 中键
                # 检查是否已经有野怪在该位置
                monster_exists = False
                for monster in self.game.monsters:
                    if monster.rect.collidepoint(event.pos):
                        monster_exists = True
                        break
                
                # 如果没有野怪，则放置一个新的
                if not monster_exists:
                    monster = Monster(self.game, event.pos[0], event.pos[1])
                    self.game.monsters.add(monster)
                else:
                    # 如果已有野怪，则删除它
                    for monster in self.game.monsters:
                        if monster.rect.collidepoint(event.pos):
                            monster.kill()
                            break

        if event.type == pygame.MOUSEBUTTONUP:
            if event.button == 1 and self.game.editor_drawing:
                self.game.editor_drawing = False
                end_pos = event.pos
                x = min(self.game.editor_start_pos[0], end_pos[0])
                y = min(self.game.editor_start_pos[1], end_pos[1])
                w = abs(end_pos[0] - self.game.editor_start_pos[0])
                h = abs(end_pos[1] - self.game.editor_start_pos[1])
                if w > 0 and h > 0:
                    obs = Obstacle(self.game, x, y, w, h)
                    self.game.obstacles.add(obs)
        
        if event.type == pygame.KEYDOWN:
            # 按 S 保存地图
            if event.key == pygame.K_s:
                self.save_map_data()

    def save_map_data(self):
        """保存地图数据"""
        # 创建maps文件夹（如果不存在）
        if not os.path.exists(MAPS_DIR):
            os.makedirs(MAPS_DIR)
        
        # 收集精灵数据用于寻路系统
        sprites_data = []
        
        # 添加障碍物数据 [type, x, y, w, h]
        for obstacle in self.game.obstacles:
            sprites_data.append({
                'type': 'obstacle',
                'x': obstacle.rect.x,
                'y': obstacle.rect.y,
                'width': obstacle.rect.width,
                'height': obstacle.rect.height
            })
        
        # 添加野怪数据 [type, x, y]
        for monster in self.game.monsters:
            sprites_data.append({
                'type': 'monster',
                'x': monster.rect.centerx,
                'y': monster.rect.centery
            })
        
        # 显示保存选项菜单
        self.show_save_options()
        
        # 预处理寻路网络
        self.preprocess_pathfinding_network(sprites_data)
    
    def preprocess_pathfinding_network(self, sprites_data):
        """预处理寻路网络"""
        try:
            # 导入寻路系统
            from pathfinding_system import PathfindingSystem
            
            # 使用当前地图文件名或默认名称初始化寻路系统
            map_filename = getattr(self.game, 'current_map_file', None) or "maps/temp.json"
            pf_system = PathfindingSystem(map_filename)
            
            # 从精灵数据中提取障碍物信息
            obstacles = [item for item in sprites_data if item.get('type') == 'obstacle']
            
            # 创建网格
            grid = pf_system.create_grid_from_map(obstacles)
            
            # 为地图中的关键点预计算路径（示例：每隔100像素计算一次）
            from settings import WIDTH, HEIGHT
            key_points = []
            for x in range(0, WIDTH, 100):
                for y in range(0, HEIGHT, 100):
                    key_points.append((x, y))
            
            # 预计算所有关键点之间的路径
            path_data = {}
            for i, start_point in enumerate(key_points):
                for j, end_point in enumerate(key_points):
                    if i != j:
                        path = pf_system.find_path(start_point[0], start_point[1], 
                                                 end_point[0], end_point[1])
                        if path:
                            path_key = f"{start_point[0]},{start_point[1]}_{end_point[0]},{end_point[1]}"
                            path_data[path_key] = path
            
            # 保存寻路数据
            pf_system.processed_paths = path_data
            pf_system.save_pathfinding_data()
            
            print(f"Pathfinding network preprocessed and saved for {map_filename}")
        except Exception as e:
            print(f"Error preprocessing pathfinding network: {e}")
    
    def show_save_options(self):
        """显示保存选项菜单"""
        # 获取所有地图文件
        map_files = self.game.get_map_files()
        
        # 如果没有地图文件，直接创建新地图
        if not map_files:
            self.create_new_map()
            return
        
        # 显示保存选项
        self.game.state = 'save_menu'
        # 保存当前状态以便返回
        self.game.previous_state = 'editor'

    def overwrite_map(self, map_file):
        """覆盖现有地图"""
        map_data = []
        # 保存障碍物数据 [type, x, y, w, h]
        for obstacle in self.game.obstacles:
            map_data.append([
                "obstacle",
                obstacle.rect.x,
                obstacle.rect.y,
                obstacle.rect.w,
                obstacle.rect.h
            ])
        
        # 保存野怪数据 [type, x, y]
        for monster in self.game.monsters:
            map_data.append([
                "monster",
                monster.rect.centerx,
                monster.rect.centery
            ])
        
        try:
            map_path = os.path.join(MAPS_DIR, map_file)
            with open(map_path, 'w') as f:
                json.dump(map_data, f)
            print(f"Map overwritten successfully as {map_file}!")
            self.game.state = self.game.previous_state
        except Exception as e:
            print(f"Error saving map: {e}")
    
    def save_map_as(self, map_name):
        """以指定名称保存地图"""
        map_data = []
        # 保存障碍物数据 [type, x, y, w, h]
        for obstacle in self.game.obstacles:
            map_data.append([
                "obstacle",
                obstacle.rect.x,
                obstacle.rect.y,
                obstacle.rect.w,
                obstacle.rect.h
            ])
        
        # 保存野怪数据 [type, x, y]
        for monster in self.game.monsters:
            map_data.append([
                "monster",
                monster.rect.centerx,
                monster.rect.centery
            ])
        
        try:
            map_path = os.path.join(MAPS_DIR, map_name)
            with open(map_path, 'w') as f:
                json.dump(map_data, f)
            print(f"Map saved successfully as {map_name}!")
            self.game.state = self.game.previous_state
        except Exception as e:
            print(f"Error saving map: {e}")
    
    def prompt_new_map_name(self):
        """提示用户输入新地图名称"""
        self.game.state = 'input_map_name'
        self.input_text = ""
        self.input_active = True
    
    def create_new_map_with_name(self, name):
        """使用指定名称创建新地图"""
        if not name:
            # 如果没有输入名称，使用默认名称
            map_name = f"map_{len(os.listdir(MAPS_DIR)) + 1}.json"
        else:
            # 确保文件名以.json结尾
            if not name.endswith('.json'):
                map_name = f"{name}.json"
            else:
                map_name = name
        
        self.save_map_as(map_name)

    def draw_editor_ui(self):
        """绘制地图编辑器界面"""
        self.game.draw_grid()
        self.game.obstacles.draw(self.game.screen)
        self.game.monsters.draw(self.game.screen)  # 绘制已放置的野怪
        self.game.draw_text("Map Editor", 48, WHITE, WIDTH / 2, 30)
        self.game.draw_text("Left Click + Drag: Create Obstacle", 24, WHITE, WIDTH / 2, 70)
        self.game.draw_text("Right Click: Delete Obstacle", 24, WHITE, WIDTH / 2, 100)
        self.game.draw_text("Middle Click: Place Monster", 24, WHITE, WIDTH / 2, 130)  # 添加野怪放置说明
        self.game.draw_text("S: Save Map | ESC: Back to Menu", 24, WHITE, WIDTH / 2, 160)